package com.tyjt.vehfinder.core.actor;

import akka.actor.AbstractActor;
import com.tyjt.common.GridInfo;
import com.tyjt.common.GridUtil;
import com.tyjt.proto.veh.Veh2CloudBsmDTO;
import com.tyjt.vehfinder.util.PubUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scala.Option;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 车辆 actor
 */
@Component("VehActor")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Slf4j
public class VehActor extends AbstractActor {
    String vehId;
    @Resource
    PubUtil pubUtil;

    static ExecutorService executorService = Executors.newFixedThreadPool(25);
    @Override
    public void preStart() throws Exception {
        super.preStart();
        vehId = getSelf().path().name();
        log.info("vehId {}  is starting  uid {}  ", vehId, getSelf().path().uid());
    }

    @Override
    public void postStop() throws Exception {
        super.postStop();
        log.error(" vehId  {}   stop uid {}  ", vehId, getSelf().path().uid());
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(StringMsg.class, this::handleStringMsg)
                .match(BsmMsg.class, this::bsmMsg)
                .matchAny(o -> log.error("{}", o)).build();
    }

    @Override
    public void aroundPreRestart(Throwable reason, Option<Object> message) {
        super.aroundPreRestart(reason, message);
        VehMgr.getInstance().getVehMap().put(vehId, getSelf());
        log.error("restart finish  {} uid {}  ", vehId, getSelf().path().uid());
    }

    private void handleStringMsg(StringMsg t) {
        int type = t.msgType;
        switch (type) {
            case 5: {
                //  todo 为了测试重启
                throw new NullPointerException("");
            }
            default:
                log.info("错误的类型");
        }

    }

    private void bsmMsg(BsmMsg msg) {
        try {
            Veh2CloudBsmDTO.Veh2CloudBsm bsm = Veh2CloudBsmDTO.Veh2CloudBsm.parseFrom(msg.getPayload());
            msg.bsm = bsm;
            GridInfo gridInfo = GridUtil.calcGridInfo(bsm.getLongitude(),bsm.getLatitude());
            //  TODO 从 数据库中获取注册时提交的数据类型
            //  从cache中获取所有的消息类型，分线程发布出去
            List<String> msgTypeList = new ArrayList<>();

//            for (String msgType : msgTypeList) {
                executorService.submit(()-> pubUtil.pub(msg,"1",gridInfo));
//            }

        } catch (Exception e) {
            log.error("", e);
        }
    }

}
